import _ from 'lodash';
import { query, create, remove, update, getDetail } from '../services/sysRole';
import createModel from './base';
import { config } from '../configs';
import { isSuccess } from '../configs/error';

const { prefix } = config;

export default createModel({
	namespace: 'sysRole',

	state: {
		permissionIds: []
	},

	subscriptions: {
		setup({ dispatch, history }) {
			dispatch({
				type: 'query'
			});
			history.listen(location => {
				if (location.pathname === '/sysRole') { // 每次刷新一下，获取最新
					dispatch({
						type: 'query'
					});
				}
			});
		},
	},

	effects: {
		*edit({ payload }, { call, put }) {
			yield put({
				type: 'set',
				payload: {
					currentItem: payload,
					permissionIds: []
				}
			});
			if (payload && payload.id) {
				const res = yield call(getDetail, payload.id);
				if (isSuccess(res)) {
					yield put({
						type: 'set',
						payload: {
							currentItem: res.data,
							permissionIds: _.get(res, 'data.permissions', []).map(p => p.permissionKey ? p.id.toString() : `v-${p.id}`)
						}
					});
				} else {
					throw res;
				}
			}
		},
	},
	reducers: {},
}, query, create, remove, update);
